<script setup>
import { ElMenu, ElMenuItem, ElAvatar, ElIcon } from 'element-plus';
import { MessageBox, Message, EditPen, Camera, ArrowLeft, Upload, Close } from '@element-plus/icons-vue';
import { ref } from 'vue';
import axios from 'axios';

axios.defaults.baseURL = 'http://localhost:8040';

const showUploadDialog = ref(false);
const selectedFile = ref(null);
const uploadProgress = ref(0);
const uploadSuccess = ref(false);
const uploadError = ref('');
// 工具函数：从Token解析用户ID（根据实际Token结构调整字段）
const getUserIdFromToken = (token) => {
  if (!token) return '';
  try {
    const payloadBase64 = token.split('.')[1];
    const decoded = JSON.parse(atob(payloadBase64));
    return decoded.sub; // 假设用户ID存放在JWT的sub字段
  } catch (error) {
    console.error('Token解析失败:', error);
    return '';
  }
};

// 获取用户ID
const token = localStorage.getItem('token');
if (!token) {
  console.log('未检测到登录态(无token)，请先登录');
}
const userId = getUserIdFromToken(token);//用户ID
if (!userId) {
  console.log("未获取到用户ID，请先登录");
} else {
  console.log("成功获取用户ID:" + userId);
}

// 用户信息
const userList = ref({
  id: '', //用户ID
  username: '',//用户名
  avatar: '',//头像
  password: '',
  phone: '',
  gender: '',
  birthday: '',
  wechatNumber: '',
  signature: '',
  region: ''
})
//根据userID查询用户信息
axios.get(`/user/selectAllById/${userId}`)
    .then(resp => {
      console.log(resp.data);
      userList.value = resp.data;  // 将返回的用户信息赋值给userList
      currentUser.value.avatar = resp.data.avatar;
      currentUser.value.name = resp.data.username;
    })
    .catch(err => {
      console.error('获取用户信息失败:', err);
    });
const currentUser = ref({
  id:userId,
  avatar: userList.value.avatar,//头像
  name: userList.value.username
});
// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    // 明确允许的视频格式
    const allowedTypes = ['video/mp4', 'video/webm', 'video/avi', 'video/mpeg'];
    if (allowedTypes.includes(file.type)) {
      selectedFile.value = file;
      uploadError.value = '';
    } else {
      uploadError.value = `不支持该文件类型（${file.type}），请选择MP4/WebM/AVI格式的视频`;
      selectedFile.value = null;
    }
  }
};



// 上传视频
const uploadVideo = async () => {
  if (!selectedFile.value) {
    uploadError.value = '请先选择视频文件';
    return;
  }

  const formData = new FormData();
  formData.append('video', selectedFile.value);
  formData.append('title', '新视频');
  formData.append('description', '这是一个新上传的视频');

  try {
    uploadProgress.value = 0;
    const response = await axios.post('/video/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progressEvent) => {
        uploadProgress.value = Math.round((progressEvent.loaded / progressEvent.total) * 100);
      }
    });

    if (response.data.code === 200) {
      uploadSuccess.value = true;
      uploadError.value = '';
      // 上传成功后刷新视频列表
      setTimeout(() => {
        showUploadDialog.value = false;
        uploadSuccess.value = false;
        selectedFile.value = null;
      }, 1500);
    } else {
      uploadError.value = response.data.msg || '上传失败';
    }
  } catch (error) {
    uploadError.value = `上传失败：${error.message}`;
    console.error('视频上传错误:', error);
  }
};

// 处理发表视频点击
const handlePublishVideo = () => {
  showUploadDialog.value = true;
};
</script>

<template>
  <router-link :to="{name:'videoview'}">
    <div class="back-button">
      <el-icon  class="back-icon">
        <ArrowLeft />
      </el-icon>
    </div>
  </router-link>

  <!-- 上传对话框 -->
  <div class="upload-dialog" v-if="showUploadDialog">
    <div class="dialog-content">
      <div class="dialog-header">
        <h3>发布新视频</h3>
        <el-icon class="close-icon" @click="showUploadDialog = false"><Close /></el-icon>
      </div>

      <div class="upload-body">
        <input
            type="file"
            accept="video/mp4,video/webm,video/ogg"
            @change="handleFileChange"
            class="file-input"
            id="file-upload"
        />
        <label for="file-upload" class="file-label">
          <el-icon :size="48"><Upload /></el-icon>
          <p>{{ selectedFile ? selectedFile.name : '点击或拖拽视频到此处' }}</p>
        </label>

        <div v-if="selectedFile" class="file-info">
          <p>文件名: {{ selectedFile.name }}</p>
          <p>大小: {{ (selectedFile.size / (1024 * 1024)).toFixed(2) }} MB</p>
        </div>

        <div v-if="uploadProgress > 0 && uploadProgress < 100" class="progress-bar">
          <div class="progress" :style="{ width: uploadProgress + '%' }"></div>
          <span>{{ uploadProgress }}%</span>
        </div>

        <div v-if="uploadSuccess" class="upload-status success">
          上传成功！
        </div>

        <div v-if="uploadError" class="upload-status error">
          {{ uploadError }}
        </div>
      </div>

      <div class="dialog-footer">
        <button
            class="cancel-btn"
            @click="showUploadDialog = false; selectedFile = null; uploadError = ''"
        >
          取消
        </button>
        <button
            class="upload-btn"
            @click="uploadVideo"
            :disabled="!selectedFile || uploadProgress > 0 && uploadProgress < 100"
        >
          确认上传
        </button>
      </div>
    </div>
  </div>

  <el-menu
      default-active="1"
      class="my-video-channel-menu"
      :collapse="false"
      :background-color="'#fff'"
      :text-color="'#333'"
      :active-text-color="'#409EFF'"
  >
    <!-- 头像及账号信息区域 -->
    <router-link :to="{name:'personalvideo'}">
      <el-menu-item index="0" style="display: flex; align-items: center; padding: 12px 20px;">
        <el-avatar :src="currentUser.avatar" style="margin-right: 10px;"></el-avatar>
        <div>
          <span class="username">{{ currentUser.name }}</span>
        </div>
      </el-menu-item>
    </router-link>
    <!-- 功能菜单区域 -->
    <el-menu-item>
      <el-icon><MessageBox /></el-icon>
      <span>视频号消息</span>
    </el-menu-item>
    <el-menu-item>
      <el-icon><Message /></el-icon>
      <span>视频号私信</span>
    </el-menu-item>
    <el-menu-item>
      <el-icon><EditPen /></el-icon>
      <span>创作者中心</span>
    </el-menu-item>
    <!-- 底部操作按钮区域 -->
    <el-menu-item index="4" style="display: flex; justify-content: space-around; border-top: 1px solid #eee; margin-top: 10px;">
      <div @click="handlePublishVideo">
        <el-icon><Camera /></el-icon>
        <span>发表视频</span>
      </div>
    </el-menu-item>
  </el-menu>
</template>


<style scoped>
.my-video-channel-menu {
  width: 220px; /* 可根据实际调整宽度 */
  border-right: none;
  height: 100vh;
  padding-top: 60px;
}
.username {
  font-size: 16px;
  font-weight: bold;
}
.follow-count {
  font-size: 12px;
  color: #999;
}
.back-button {
  position: absolute;
  top: 16px;
  left: 16px;
  z-index: 10;
}

.back-icon {
  cursor: pointer;
  font-size: 20px;
  color: #333;
}

/* 上传对话框样式 */
.upload-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  width: 90%;
  max-width: 500px;
  background-color: white;
  border-radius: 10px;
  overflow: hidden;
}

.dialog-header {
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.close-icon {
  cursor: pointer;
  color: #999;
}

.close-icon:hover {
  color: #333;
}

.upload-body {
  padding: 20px;
}

.file-input {
  display: none;
}

.file-label {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  border: 2px dashed #ddd;
  border-radius: 8px;
  cursor: pointer;
  transition: border-color 0.3s;
  color: #666;
}

.file-label:hover {
  border-color: #409eff;
}

.file-info {
  margin-top: 20px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-size: 14px;
}

.progress-bar {
  margin-top: 20px;
  height: 8px;
  background-color: #eee;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}

.progress {
  height: 100%;
  background-color: #409eff;
  transition: width 0.3s;
}

.progress-bar span {
  position: absolute;
  right: 10px;
  top: -20px;
  font-size: 12px;
  color: #666;
}

.upload-status {
  margin-top: 20px;
  padding: 10px;
  border-radius: 4px;
  font-size: 14px;
  text-align: center;
}

.success {
  background-color: #f0f9eb;
  color: #52c41a;
}

.error {
  background-color: #fff2f0;
  color: #f5222d;
}

.dialog-footer {
  padding: 16px 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn, .upload-btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  border: 1px solid #ddd;
}

.cancel-btn {
  background-color: white;
  color: #666;
}

.cancel-btn:hover {
  background-color: #f5f5f5;
}

.upload-btn {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.upload-btn:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}
</style>